package com.neusoft.lohas.modules.ivm.web.purchase;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.pay.payutil.alipay.util.UtilDate;
import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.persistence.StatusBean;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.utils.PinYinHeadCharUtil;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.utils.excel.ExcelManager;
import com.neusoft.lohas.common.utils.excel.ExportExcel;
import com.neusoft.lohas.common.web.BaseController;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryMember;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductInventoryDetail;
import com.neusoft.lohas.modules.ivm.entity.product.Supplier;
import com.neusoft.lohas.modules.ivm.entity.purchase.Purchase;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetail;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetailItem;
import com.neusoft.lohas.modules.ivm.service.order.OrderService;
import com.neusoft.lohas.modules.ivm.service.product.ProductInventoryDetailService;
import com.neusoft.lohas.modules.ivm.service.product.ProductService;
import com.neusoft.lohas.modules.ivm.service.purchase.PurchaseDetailService;
import com.neusoft.lohas.modules.ivm.service.purchase.PurchaseService;
import com.neusoft.lohas.modules.ivm.utils.MerchantUtils;
import com.neusoft.lohas.modules.ivm.utils.ProductUtils;

/**
 * 采购清单Controller
 * @author jackie.liu
 * @version 2014-12-31
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/ivm/purchase")
public class PurchaseController extends BaseController{

	@Autowired
	private ProductService productService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private PurchaseDetailService purchaseDetailService;
	@Autowired
	private PurchaseService purchaseService;
	@Autowired
	private ExcelManager excelManager;
	@Autowired
	private ProductInventoryDetailService productInventoryDetailService;
	
	//采购编号(包括采购令)
	public String createUniqeAuthCode() {
		Merchant merchant = super.merchant;
		String merchantSP = PinYinHeadCharUtil.getPinYinHeadChar(merchant.getName());
		if(merchantSP.length()>4){
			merchantSP = merchantSP.substring(0, 4);//商户名前四位
		}
		int orderNums = purchaseService.getOrderNumsByDate(merchant.getId())+1;//获取当日采购总数
		String threeRandom = UtilDate.getThree(orderNums+"");//组装三位数
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmssSSS");// 设置日期格式
		String orderNo = df.format(new Date());// new Date()为获取当前系统时间
		String authCode = "PO"+merchantSP+orderNo.substring(0, 6) + threeRandom;
		return authCode;
	}
	
	/**
	 * 生成采购清单
	 * @param orderIds
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showPurchaseOrder")
	public String showPurchaseOrder(String orderIds,
			@RequestParam(value="supplierId", required=false, defaultValue="") String supplierId,
			@RequestParam(value="purchaseState", required=false, defaultValue="0")int purchaseState,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		List<PurchaseDetail> detailList= orderService.getOrderPurchaseList(orderIds, supplierId, purchaseState,1);
		//获取所有供应商
		List<Supplier> supplierList = ProductUtils.getSupplierList();
//		List<Supplier> supplierList = Lists.newArrayList();
//		for (PurchaseDetail detail : detailList) {
//			boolean isExists = false;
//			for (Supplier supplier : supplierList) {
//				if (detail.getProduct().getDefaultSupplier()!=null && detail.getProduct().getDefaultSupplier().getId().equals(supplier.getId())) {
//					isExists = true;
//				}
//			}
//			if (!isExists && detail.getProduct().getDefaultSupplier()!=null) {
//				supplierList.add(detail.getProduct().getDefaultSupplier());
//			}
//		}
		model.addAttribute("supplierId", supplierId);
		model.addAttribute("purchaseState", purchaseState);
		model.addAttribute("supplierList", supplierList);
		model.addAttribute("detailList",detailList);
		model.addAttribute("merchant", super.merchant);
		model.addAttribute("orderIds", orderIds);
		return "modules/ivm/order/purchaseorder/purchaseOrderDetail";
	}
	
	/**
	 * 生成配送清单
	 * @param orderIds
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showDistributionOrder")
	public String showDistributionOrder(String orderIds,
			@RequestParam(value="supplierId", required=false, defaultValue="") String supplierId,
			@RequestParam(value="purchaseState", required=false, defaultValue="0")int purchaseState,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		List<PurchaseDetail> detailList= orderService.getOrderPurchaseList(orderIds, supplierId, purchaseState,1);
		//获取所有供应商
		List<Supplier> supplierList = ProductUtils.getSupplierList();
		//合并重复的商品
		Map<String, PurchaseDetail> map = new HashedMap();
		List<PurchaseDetail> repeatPurchaseList = Lists.newArrayList();//重复记录的PurchaseDetail
		for(PurchaseDetail purchaseDetail: detailList){
			if(map.containsKey(purchaseDetail.getProduct().getId())){
				int hasNum = map.get(purchaseDetail.getProduct().getId()).getBuyNumber(); //已记录的数量
				int thisNum = purchaseDetail.getBuyNumber(); //改记录的数量
				int totalNum = hasNum + thisNum; //总数
				map.get(purchaseDetail.getProduct().getId()).setBuyNumber(totalNum);
				repeatPurchaseList.add(purchaseDetail);
			}else{
				map.put(purchaseDetail.getProduct().getId(), purchaseDetail);
			}
		}
		//从supplierList移除重复的对象
		List<PurchaseDetail> newPurchaseList = Lists.newArrayList();
		for (Map.Entry<String, PurchaseDetail> entry : map.entrySet()) {
			newPurchaseList.add(entry.getValue());
		}
		model.addAttribute("supplierId", supplierId);
		model.addAttribute("purchaseState", purchaseState);
		model.addAttribute("supplierList", supplierList);
		model.addAttribute("detailList",newPurchaseList);
		model.addAttribute("merchant", super.merchant);
		model.addAttribute("orderIds", orderIds);
		return "modules/ivm/order/purchaseorder/distributionOrderDetail";
	}
	
	/**
	 * 生成采购指令
	 * @param memberId
	 * @param detailList
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "createPurchase")
	public @ResponseBody Object createPurchase(String memberId, String supplierId, String detailList, HttpServletRequest request, HttpServletResponse response){
		String merchantId = MerchantUtils.getMerchant().getId();
		//解析数据
		Purchase purchase = new Purchase();
		//获取采购清单信息
		String purchaseId = IdGen.uuid();
		//设置采购指令信息
		purchase.setId(purchaseId);
		purchase.setMember(new DeliveryMember(memberId));
		purchase.setSupplier(new Supplier(supplierId));
		purchase.setMerchant(new Merchant(merchantId));
		purchase.setCode(this.createUniqeAuthCode());
		purchase.prePersist(); //insert执行
		
		//获取采购指令明细
		List<PurchaseDetail> details = Lists.newArrayList();
		//做去重处理的集合
		List<String> detailIds = Lists.newArrayList();
		//获取采购指令明细对应的明细，即商品不合并的每个商品采购数量信息
		List<PurchaseDetailItem> detailItemList = Lists.newArrayList();
		for (String item : detailList.split(",")) {
			String[] dt = item.split(":");
			boolean isExists = false;
			if (details.size()>0) {
				for (PurchaseDetail bean : details) {
					if (bean.getProduct().getId().equals(dt[2])) {
						isExists = true; 
						Order order = orderService.get(dt[1]);
						if(!bean.getOrderList().contains(order)){
							bean.getOrderList().add(order);
						}
						bean.setPurchaseNumber(bean.getPurchaseNumber()+Integer.valueOf(dt[3]));
						
						//构建采购指令明细的明细信息
						PurchaseDetailItem detailItem = new PurchaseDetailItem();
						detailItem.setId(IdGen.uuid());
						detailItem.setMerchant(new Merchant(merchantId));
						detailItem.setOrder(order);
						detailItem.setProduct(new Product(dt[2]));
						detailItem.setPurchase(purchase);
						detailItem.setPurchaseNumber(Integer.valueOf(dt[3]));
						detailItem.prePersist();
						detailItemList.add(detailItem);
						break;
					}
				}
			}
			if (!isExists) {  //如果当前result已经存在了该商品清单,则在其基础上累加购买量
				PurchaseDetail detail = new PurchaseDetail();
				String detailId = IdGen.uuid();
				//存在重复主键则重新生成，直接不重复为止
				while (1>0) {
					if(!detailIds.contains(detailId)){
						detailIds.add(detailId);
						break;
					}
					detailId = IdGen.uuid();
				}
				detail.setId(detailId);
				detail.setMerchant(new Merchant(merchantId));
				detail.setPurchase(purchase);
				detail.setType(Integer.valueOf(dt[0]));
				Order order = orderService.get(dt[1]);
				detail.getOrderList().add(order);
				detail.setProduct(new Product(dt[2]));
				detail.setPurchaseNumber(Integer.valueOf(dt[3]));
				detail.prePersist(); //insert执行
				details.add(detail);
				//System.out.println(detail.getId()+"-"+order.getId());
				
				//构建采购指令明细的明细信息
				PurchaseDetailItem detailItem = new PurchaseDetailItem();
				detailItem.setId(IdGen.uuid());
				detailItem.setMerchant(new Merchant(merchantId));
				detailItem.setOrder(order);
				detailItem.setProduct(new Product(dt[2]));
				detailItem.setPurchase(purchase);
				detailItem.setPurchaseNumber(Integer.valueOf(dt[3]));
				detailItem.prePersist();
				detailItemList.add(detailItem);
			}
		}
		purchase.setDetailItemList(detailItemList);
		//保存采购指令信息
		purchaseService.save(purchase);
		//保存采购指令明细（并且联动保存明细和订单关系数据）
		purchaseDetailService.save(details);
		
		return getStatusBean(200, "采购指令生成成功:"+purchaseId);
	}
	
	/**
	 * 手动添加采购清单
	 * @param merchantId
	 * @param infoId
	 * @param code
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "createHmPurchase")
	public @ResponseBody Object createHmPurchase(String merchantId, int code, HttpServletRequest request, HttpServletResponse response){
		PurchaseDetail purchaseDetail = new PurchaseDetail();
		purchaseDetail.setMerchant(new Merchant(merchantId));
		Product product = productService.getProductByCode(merchantId, String.valueOf(code));
		List<ProductInventoryDetail> inventoryDetailList = product.getInventoryDetailList();
		purchaseDetail.setProduct(product);
		purchaseDetail.setType(2);
		purchaseDetail.setPurchaseNumber(product.getSpecNum());
		if (inventoryDetailList.size()>0) {
			ProductInventoryDetail inventoryDetail = inventoryDetailList.get(inventoryDetailList.size()-1);
			purchaseDetail.setReferencePrice(FloatFormat.m2_2(product.getSpecNum()*inventoryDetail.getAmount()/inventoryDetail.getWeight()));
		}
		StatusBean<PurchaseDetail> result = new StatusBean<PurchaseDetail>(purchaseDetail, 200, "成功");
		return result;
	}
	
	@RequiresPermissions("ivm:purchase:view")
	@RequestMapping(value = {"list", ""})
	public String list(Purchase purchase, 
			@RequestParam(value="hopeDate", required=false, defaultValue="") String hopeDate,
			@RequestParam(value="searchParam", required=false, defaultValue="") String searchParam,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		purchase.setMerchant(super.merchant);
        Page<Purchase> page = purchaseService.find(new Page<Purchase>(request, response), purchase, hopeDate, searchParam); 
        model.addAttribute("page", page);
        model.addAttribute("purchase", purchase);
        model.addAttribute("hopeDate", hopeDate);
        model.addAttribute("searchParam", searchParam);
		return "modules/ivm/order/purchase/purchaseList";
	}
	
	@RequiresPermissions("ivm:purchase:view")
	@RequestMapping(value = "showPurchaseDetail")
	public String showPurchaseDetail(Purchase purchase, 
			HttpServletRequest request, HttpServletResponse response, Model model) {
		purchase = purchaseService.get(purchase.getId());
        model.addAttribute("purchase", purchase);
        model.addAttribute("type", "");
		return "modules/ivm/order/purchase/purchaseDetail";
	}
	
	//新增采购指令面板
	@RequiresPermissions("ivm:purchase:view")
	@RequestMapping(value = "showNewPurchase")
	public String showNewPurchase(HttpServletRequest request, HttpServletResponse response, Model model) {
		Purchase purchase = new Purchase();
		purchase.setMerchant(super.merchant);
        model.addAttribute("purchase", purchase);
        //获取所有供应商
		List<Supplier> supplierList = ProductUtils.getSupplierList();
		model.addAttribute("supplierList", supplierList);
		return "modules/ivm/order/purchase/newPurchaseDetail";
	}
	
	@RequiresPermissions("ivm:purchase:view")
	@RequestMapping(value = "previewPurchaseDetail")
	public String previewPurchaseDetail(Purchase purchase, 
			HttpServletRequest request, HttpServletResponse response, Model model) {
		purchase = purchaseService.get(purchase.getId());
        model.addAttribute("purchase", purchase);
		return "modules/ivm/order/purchase/previewPurchaseDetail";
	}
	
	/**
	 * 跳转采购清单商品对应订单详情
	 * @param id 采购清单明细Id
	 * @param type 1为采购清单主表过来获取，2为采购清单明细表过来获取
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showOrderDetail")
	public String showOrderDetail(String id, int type, HttpServletRequest request, HttpServletResponse response, Model model){
		List<Order> list = Lists.newArrayList();
		if (type==1) {
			list = purchaseDetailService.get(id).getOrderList();
		}else if(type==2){
			list = purchaseDetailService.getOrderDetails(id);
		}
		model.addAttribute("list", list);
		return "modules/ivm/order/purchase/orderDetail";
	}
	
	/**
	 * 删除采购指令（同时删除子数据）
	 * @param id
	 * @param detailId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "deletePurchase")
	public String deletePurchase(String id, HttpServletRequest request, HttpServletResponse response, Model model){
		Purchase purchase = purchaseService.get(id);
		//删除没有合并生成的采购指令明细数据
		for(PurchaseDetailItem detailItem:purchase.getDetailItemList()){
			purchaseDetailService.deletePurchaseDetailItem(id,detailItem.getProduct().getId());
		}
		//删除明细记录
		for(PurchaseDetail detail:purchase.getDetailList()){
			purchaseDetailService.delete(detail.getId());
		}
		//删除采购指令
		purchaseService.delete(id);
		return "redirect:"+Global.getAdminPath()+"/ivm/purchase";
	}
	
	/**
	 * 删除采购清单明细信息
	 * @param id
	 * @param detailId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "deletePurchaseDetail")
	public @ResponseBody Object deletePurchaseDetail(String id, RedirectAttributes redirectAttributes){
		PurchaseDetail detail = purchaseDetailService.get(id);
		int result = purchaseDetailService.delete(id);
		//删除没有合并生成的采购指令明细数据
		purchaseDetailService.deletePurchaseDetailItem(detail.getPurchase().getId(), detail.getProduct().getId());
		if (result>0) {
			return getStatusBean(200, "删除采购指令明细成功");
		}else {
			return getStatusBean(500, "删除采购指令明细失败");
		}
	}
	
	@RequestMapping(value = "updateState")
	public String updateState(String id, String state, RedirectAttributes redirectAttributes, Model model){
		Purchase purchase = purchaseService.get(id);
		purchase.setState(state);
		purchase.setMerchant(super.merchant);
		purchaseService.save(purchase);
		for (PurchaseDetail detail : purchase.getDetailList()) {
			detail.setState("1");
		}
		purchaseDetailService.save(purchase.getDetailList());
		//addMessage(redirectAttributes, "修改采购令成功");
		//return "redirect:"+Global.getAdminPath()+"/ivm/purchase?repage";
		model.addAttribute("purchase", purchase);
		model.addAttribute("message", "修改采购令成功");
		model.addAttribute("type", "完成采购单");
		return "modules/ivm/order/purchase/purchaseDetail";
	}
	
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		Purchase purchase = purchaseService.get(id);
		purchaseService.delete(id);
		for (PurchaseDetail detail : purchase.getDetailList()) {
			detail.setDelFlag(PurchaseDetail.DEL_FLAG_DELETE);
		}
		purchaseDetailService.save(purchase.getDetailList());
		addMessage(redirectAttributes, "删除采购令成功");
		return "redirect:"+Global.getAdminPath()+"/ivm/purchase?repage";
	}
	
	@RequestMapping(value = "updatePurchaseDetailState")
	public @ResponseBody Object updatePurchaseDetailState(String id, String state, RedirectAttributes redirectAttributes){
		PurchaseDetail purchaseDetail = purchaseDetailService.get(id);
		purchaseDetail.setState(state);
		purchaseDetailService.save(purchaseDetail);
		Purchase purchase = purchaseDetail.getPurchase();
		if (purchase.getPurchaseFinishedNum()==purchase.getDetailList().size()) {
			purchase.setState("1");
			purchaseService.save(purchase);
		}
		return getStatusBean(200, "修改采购成功");
	}
	
	/**
	 * 保存采购指令明细
	 * @param detailList:采购商品
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "savePurchaseDetail")
	public @ResponseBody Object savePurchaseDetail(String purchaseId, String memberId, String detailList, HttpServletRequest request, HttpServletResponse response){
		Purchase purchase = purchaseService.get(purchaseId);
		purchase.setMember(new DeliveryMember(memberId));
		String state = "0";//采购指令状态 0 未完成，2部分完成
		//获取采购指令明细
		List<PurchaseDetail> details = Lists.newArrayList();
		//入库记录list
		List<ProductInventoryDetail> inventoryDetails = Lists.newArrayList();
		if(StringUtils.isNotBlank(detailList)){
			for (String item : detailList.split(",")) {
				String[] dt = item.split(":");
				//采购清单
				PurchaseDetail detail = new PurchaseDetail();
				if (StringUtils.isNotBlank(dt[0])) {
					detail = purchaseDetailService.get(dt[0]);
				}else{
					detail.setId(IdGen.uuid());
					detail.prePersist(); //insert执行
				}
				detail.setMerchant(MerchantUtils.getMerchant());
				detail.setPurchase(new Purchase(purchaseId));
				detail.setType(Integer.valueOf(dt[1]));
				detail.setProduct(new Product(dt[3]));
				detail.setPurchaseNumber(Integer.valueOf(dt[4]));
				if(StringUtils.isNotBlank(dt[5])){
					if(Integer.valueOf(dt[5])>=Integer.valueOf(dt[4])){
						detail.setState("2");
						state="2";
					}else if(Integer.valueOf(dt[5])==0){
						detail.setState("0");
					}else{
						detail.setState("1");
						state="2";
					}
				}
				detail.setAdviceNumber(Integer.valueOf(dt[8]));
				details.add(detail);
				//入库记录
				ProductInventoryDetail inventoryDetail = new ProductInventoryDetail();
				//入库记录的入库量
				int intoNum = 0;
				//新的入库数量
				int newNum = Integer.valueOf(dt[5]);
				//入库改变数量
				int changeNum = 0;
				if (StringUtils.isNotBlank(dt[7])) {//入库记录ID
					inventoryDetail = productInventoryDetailService.get(dt[7]);
					//入库数量
					intoNum = inventoryDetail.getWinWeight();
				}else{
					inventoryDetail.setId(IdGen.uuid());
					inventoryDetail.prePersist(); //insert执行
				}
				changeNum = newNum-intoNum;
				inventoryDetail.setMerchant(merchant);
				Product product = productService.get(dt[3]);
				//更新库存
				product.setStock(product.getStock()+changeNum);
				productService.save(product);
				inventoryDetail.setProduct(product);
				inventoryDetail.setWeight(Integer.valueOf(dt[5]));
				inventoryDetail.setMember(purchase.getMember());
				inventoryDetail.setWinWeight(Integer.valueOf(dt[5]));
				inventoryDetail.setLossWeight(0);
				inventoryDetail.setAmount(Double.valueOf(dt[6]));
				inventoryDetail.setSupplier(purchase.getSupplier());
				inventoryDetail.setPurchase(purchase);
				inventoryDetails.add(inventoryDetail);
			}
			//保存采购指令明细（并且联动保存明细和订单关系数据）
			purchaseDetailService.save(details);
			//保存入库信息
			for(ProductInventoryDetail inventoryDetail:inventoryDetails){
				productInventoryDetailService.save(inventoryDetail);
			}
		}
		purchase.setState(state);
		purchaseService.save(purchase);
		return getStatusBean(200, "采购指令明细保存成功");
	}
	
	@RequiresPermissions("ivm:purchase:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Purchase purchase, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			purchase = purchaseService.get(purchase.getId());
            String fileName = purchase.getCode()+purchase.getSupplier().getName()+purchase.getMember().getName()+".xlsx"; 
    		new ExportExcel(purchase.getCode()+purchase.getSupplier().getName()+purchase.getMember().getName(), PurchaseDetail.class).setDataList(purchase.getDetailList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出采购指令明细失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ivm/purchase/?repage";
    }
	
	/**
	 * 导出配送清单
	 */
    @RequestMapping(value = "exportDistribution", method=RequestMethod.POST)
    public @ResponseBody Object exportFile(String orderIds, String supplierId, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String filePath = null;
	    String fileURL = null;
		try {
			List<PurchaseDetail> detailList= orderService.getOrderPurchaseList(orderIds, supplierId, 0, 1);
			//合并重复的商品
			Map<String, PurchaseDetail> map = new HashedMap();
			List<PurchaseDetail> repeatPurchaseList = Lists.newArrayList();//重复记录的PurchaseDetail
			for(PurchaseDetail purchaseDetail: detailList){
				if(map.containsKey(purchaseDetail.getProduct().getId())){
					int hasNum = map.get(purchaseDetail.getProduct().getId()).getBuyNumber(); //已记录的数量
					int thisNum = purchaseDetail.getBuyNumber(); //改记录的数量
					int totalNum = hasNum + thisNum; //总数
					map.get(purchaseDetail.getProduct().getId()).setBuyNumber(totalNum);
					repeatPurchaseList.add(purchaseDetail);
				}else{
					map.put(purchaseDetail.getProduct().getId(), purchaseDetail);
				}
			}
			//从supplierList移除重复的对象
			List<PurchaseDetail> newPurchaseList = Lists.newArrayList();
			for (Map.Entry<String, PurchaseDetail> entry : map.entrySet()) {
				newPurchaseList.add(entry.getValue());
			}
		    //获取文件保存路径
		    String url=Global.getConfig("upload.path")+"DistributionList.xls";
			filePath = url.split(",")[0];
			fileURL = url.split(",")[0];
			File excelFile = new File(filePath);
			excelFile.createNewFile();
			//构建数据
			//生成excel数据列的标题
			String columnValue = "商品编号,商品名称,商品规格,配货数量,已配份数,缺货份数";
			String[] columnValues = columnValue.split(",");
			List<String> columns = new ArrayList<String>();
			for (int i=0; i<columnValues.length; i++) {
					columns.add(columnValues[i]);
			}
			//生成excel单元格数据
			//生成excel单元格数据-第1行的数据
			Map<String, List<String>> data = new LinkedHashMap<String, List<String>>();
			List<String> rowData = new ArrayList<String>();
			for(PurchaseDetail purchaseDetail: newPurchaseList){
				rowData = new ArrayList<String>();
				rowData.add(purchaseDetail.getProduct().getCode()+"");
				rowData.add(purchaseDetail.getProduct().getName());
				rowData.add(purchaseDetail.getProduct().getAssisTitle());
				if(purchaseDetail.getProduct().getProductUnit() != null){
					rowData.add(purchaseDetail.getBuyNumber()+purchaseDetail.getProduct().getProductUnit().getName());
				}else{
					rowData.add(purchaseDetail.getBuyNumber()+"");
				}
				rowData.add("");
				rowData.add("");
				data.put(purchaseDetail.getProduct().getId()+"", rowData);
			}
			//调用ExcelManager对象write数据
			excelManager.writeExcel(excelFile, "sheet", columns, data);
			//返回文件名
			//response.getWriter().print(fileURL);
		} catch (Exception e) {
			return getStatusBean(400, "配送单导出失败");
		}
		//return "redirect:"+Global.getAdminPath()+"/ivm/order/?repage";
		return getStatusBean(200, fileURL);
    }
}
